<template>
  <div class="user-profile">
    <a-row :gutter="24">
      <a-col :span="14">
        <a-card title="个人资料" :bordered="false">
          <a-form
            :model="formState"
            name="userProfile"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 16 }"
            @finish="onFinish"
          >
            <a-form-item label="头像">
              <avatar-upload
                v-model:value="formState.userAvatar"
                @upload-success="handleAvatarSuccess"
              />
            </a-form-item>

            <a-form-item label="昵称" name="userName">
              <a-input v-model:value="formState.userName" placeholder="请输入昵称" />
            </a-form-item>

            <a-form-item label="个人简介" name="userProfile">
              <a-textarea
                v-model:value="formState.userProfile"
                :rows="4"
                placeholder="请输入个人简介"
              />
            </a-form-item>

            <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
              <a-button type="primary" html-type="submit">保存修改</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>

      <a-col :span="10">
        <a-card title="修改密码" :bordered="false">
          <a-form
            :model="passwordForm"
            name="passwordForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
            @finish="onPasswordFinish"
          >
            <a-form-item
              label="原密码"
              name="oldPassword"
              :rules="[{ required: true, message: '请输入原密码' }]"
            >
              <a-input-password v-model:value="passwordForm.oldPassword" />
            </a-form-item>

            <a-form-item
              label="新密码"
              name="newPassword"
              :rules="[
                { required: true, message: '请输入新密码' },
                { min: 8, message: '密码长度不能小于8位' },
              ]"
            >
              <a-input-password v-model:value="passwordForm.newPassword" />
            </a-form-item>

            <a-form-item
              label="确认新密码"
              name="confirmPassword"
              :rules="[
                { required: true, message: '请确认新密码' },
                { validator: validateConfirmPassword },
              ]"
            >
              <a-input-password v-model:value="passwordForm.confirmPassword" />
            </a-form-item>

            <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
              <a-button type="primary" html-type="submit">修改密码</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import AvatarUpload from '@/components/AvatarUpload.vue'
import { userEditUsingPost, updateUserPasswordUsingPost } from '@/api/userController'
import { useRouter } from 'vue-router'

const router = useRouter()
const loginUserStore = useLoginUserStore()

const formState = ref({
  userName: '',
  userProfile: '',
  userAvatar: '',
})

onMounted(() => {
  const loginUser = loginUserStore.loginUser
  formState.value = {
    userName: loginUser.userName || '',
    userProfile: loginUser.userProfile || '',
    userAvatar: loginUser.userAvatar || '',
  }
})

const handleAvatarSuccess = async (url: string) => {
  formState.value.userAvatar = url
  // 上传头像成功后，立即更新用户信息
  try {
    const res = await userEditUsingPost({
      ...formState.value,
      id: loginUserStore.loginUser.id,
      userAvatar: url,
    })
    if (res.data.code === 0) {
      message.success('头像更新成功')
      // 更新全局用户信息
      loginUserStore.setLoginUser({
        ...loginUserStore.loginUser,
        ...formState.value,
        userAvatar: url,
      })
    } else {
      message.error('头像更新失败：' + res.data.message)
    }
  } catch (error) {
    message.error('头像更新失败，请重试')
  }
}

const onFinish = async (values: any) => {
  try {
    const res = await userEditUsingPost({
      ...values,
      id: loginUserStore.loginUser.id,
      userAvatar: formState.value.userAvatar,
    })
    if (res.data.code === 0) {
      message.success('更新成功')
      // 更新全局用户信息
      loginUserStore.setLoginUser({
        ...loginUserStore.loginUser,
        ...values,
        userAvatar: formState.value.userAvatar,
      })
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error) {
    message.error('更新失败，请重试')
  }
}

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 验证确认密码
const validateConfirmPassword = async (_rule: any, value: string) => {
  if (value !== passwordForm.value.newPassword) {
    return Promise.reject('两次输入的密码不一致')
  }
  return Promise.resolve()
}

// 提交修改密码
const onPasswordFinish = async (values: any) => {
  try {
    const res = await updateUserPasswordUsingPost({
      oldPassword: values.oldPassword,
      newPassword: values.newPassword,
    })
    if (res.data.code === 0) {
      message.success('密码修改成功，请重新登录')
      // 退出登录，跳转到登录页
      loginUserStore.setLoginUser({
        userName: '未登录',
      })
      await router.push('/user/login')
    } else {
      message.error('修改失败：' + res.data.message)
    }
  } catch (error) {
    message.error('修改失败，请重试')
  }
}
</script>

<style scoped>
.user-profile {
  padding: 24px;
  background: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.ant-card {
  margin-bottom: 24px;
}
</style>
